// src/renderer/store/modules/marketData.js
import { defineStore } from 'pinia';
// 使用简化版API
import { fetchRegionCategories, fetchRegionData } from '../api/simplified-marketApi';

export const useMarketDataStore = defineStore('marketData', {
  state: () => ({
    regionCategories: [],
    regionData: [],
    loading: false,
    error: null,
    currentCategory: 'region'
  }),
  
  getters: {
    categorizedRegions: (state) => {
      const result = {};
      
      state.regionCategories.forEach(category => {
        const letterRange = category.letter;
        if (!result[letterRange]) {
          result[letterRange] = [];
        }
        
        category.regions.forEach(region => {
          result[letterRange].push(region);
        });
      });
      
      return result;
    }
  },
  
  actions: {
    setCurrentCategory(category) {
      this.currentCategory = category;
    },
    
    async fetchRegionCategories() {
      this.loading = true;
      this.error = null;
      
      try {
        const data = await fetchRegionCategories();
        if (data && data.length > 0) {
          this.regionCategories = data;
        } else {
          console.warn('No region category data received, using fallback data');
          this.regionCategories = [
            {
              letter: 'A~E',
              regions: [
                { name: '安徽', code: '882001', url: 'http://q.10jqka.com.cn/dy/detail/code/882001/' },
                { name: '北京', code: '882002', url: 'http://q.10jqka.com.cn/dy/detail/code/882002/' }
              ]
            },
            {
              letter: 'F~J',
              regions: [
                { name: '福建', code: '882005', url: 'http://q.10jqka.com.cn/dy/detail/code/882005/' },
                { name: '广东(除深圳)', code: '882008', url: 'http://q.10jqka.com.cn/dy/detail/code/882008/' },
                { name: '广西', code: '882009', url: 'http://q.10jqka.com.cn/dy/detail/code/882009/' }
              ]
            },
            {
              letter: 'K~O',
              regions: [
                { name: '内蒙古', code: '882020', url: 'http://q.10jqka.com.cn/dy/detail/code/882020/' }
              ]
            }
          ];
        }
      } catch (err) {
        this.error = err.message || 'Failed to fetch region categories';
        console.error('Error fetching region categories:', err);
        this.regionCategories = [
          {
            letter: 'A~E',
            regions: [
              { name: '安徽', code: '882001', url: 'http://q.10jqka.com.cn/dy/detail/code/882001/' },
              { name: '北京', code: '882002', url: 'http://q.10jqka.com.cn/dy/detail/code/882002/' }
            ]
          },
          {
            letter: 'F~J',
            regions: [
              { name: '福建', code: '882005', url: 'http://q.10jqka.com.cn/dy/detail/code/882005/' },
              { name: '广东(除深圳)', code: '882008', url: 'http://q.10jqka.com.cn/dy/detail/code/882008/' },
              { name: '广西', code: '882009', url: 'http://q.10jqka.com.cn/dy/detail/code/882009/' }
            ]
          }
        ];
      } finally {
        this.loading = false;
      }
    },
    
    async fetchRegionData() {
      this.loading = true;
      this.error = null;
      
      try {
        const data = await fetchRegionData();
        if (data && data.length > 0) {
          this.regionData = data;
        } else {
          console.warn('No region data received, using fallback data');
          this.regionData = [
            {
              rank: '1',
              region: {
                name: '内蒙古',
                url: 'http://q.10jqka.com.cn/dy/detail/code/882020/',
                code: '882020'
              },
              change: {
                value: '-0.41',
                isNegative: true
              },
              volume: '1087.64',
              amount: '91.18',
              netflow: '-3.49',
              upCount: '12',
              downCount: '15',
              avgPrice: '8.38',
              leadingStock: {
                name: '天和磁材',
                url: 'http://stockpage.10jqka.com.cn/603072/',
                latestPrice: '44.86',
                change: '10.01'
              }
            },
            {
              rank: '2',
              region: {
                name: '云南',
                url: 'http://q.10jqka.com.cn/dy/detail/code/882032/',
                code: '882032'
              },
              change: {
                value: '-0.86',
                isNegative: true
              },
              volume: '1364.84',
              amount: '136.33',
              netflow: '-2.11',
              upCount: '15',
              downCount: '24',
              avgPrice: '9.99',
              leadingStock: {
                name: '川金诺',
                url: 'http://stockpage.10jqka.com.cn/300505/',
                latestPrice: '17.25',
                change: '9.59'
              }
            }
          ];
        }
      } catch (err) {
        this.error = err.message || 'Failed to fetch region data';
        console.error('Error fetching region data:', err);
        this.regionData = [
          {
            rank: '1',
            region: {
              name: '内蒙古',
              url: 'http://q.10jqka.com.cn/dy/detail/code/882020/',
              code: '882020'
            },
            change: {
              value: '-0.41',
              isNegative: true
            },
            volume: '1087.64',
            amount: '91.18',
            netflow: '-3.49',
            upCount: '12',
            downCount: '15',
            avgPrice: '8.38',
            leadingStock: {
              name: '天和磁材',
              url: 'http://stockpage.10jqka.com.cn/603072/',
              latestPrice: '44.86',
              change: '10.01'
            }
          }
        ];
      } finally {
        this.loading = false;
      }
    },
    
    async loadAllRegionData() {
      await Promise.all([
        this.fetchRegionCategories(),
        this.fetchRegionData()
      ]);
    }
  }
});